package com.study.spmongodb.wwj.juc.utils;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 14:18
 */
public class SemaphoreExample {

    public static void main(String[] args) {

        final SemaphoreLock lock = new SemaphoreLock();
        new Thread(() -> {
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " get the lock");
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("release lock");
                lock.unlock();
            }
        }).start();
    }

    static class SemaphoreLock {
        final Semaphore semaphore = new Semaphore(1);

        public void lock() throws InterruptedException {
            semaphore.acquire();
        }

        public void unlock() {
            semaphore.release();
        }
    }
}
